/* eslint-disable react/display-name */
import React from 'react'
import { Table, Divider, Modal, message } from 'antd'
import { Link } from 'dva/router'
import propTypes from 'prop-types'
import gql from 'graphql-tag'
import { GQL as AGQL } from '../../../components/GQL'

// 删除数据
const Delete = ({ delGroups, record, refetch }) => {
  return (
    <a onClick={() => Confirm(record, delGroups, refetch)} ><span>删除</span></a>
  )
}
const DeleteAGQL = AGQL({
  mutation: gql`
    mutation delGroups($ids: Int!){
      delGroups(ids: $ids) {
        status
        message
      }
  }`,
  name: 'delGroups'
})(Delete)

function Confirm ({ groupId }, del, refetch) {
  Modal.confirm({
    content: '确定要删除选中的项?',
    okText: '确认',
    cancelText: '取消',
    onOk () {
      del({ variables: { ids: groupId } }).then(res => {
        message.success(res.data.delGroups.message)
        refetch()
      }).catch(err => {
        console.log(err)
      })
    }
  })
}

function CustomTable ({ dataSource, loading, refetch, dispatch }) {
  const columns = [{
    title: ' ',
    dataIndex: 'index',
    width: 50,
    render: (text, record, index) => index + 1
  }, {
    title: '名称',
    dataIndex: 'groupName',
    width: '20%'
  }, {
    title: '权限',
    dataIndex: 'ruleGroupNames',
    width: '40%',
    render: (text, record) => record.isAdministrator ? '所有权限' : text
  }, {
    title: '更新时间',
    dataIndex: 'updateDate',
    width: '40%'
  }, {
    title: '操作',
    dataIndex: 'todo',
    width: 150,
    render: (text, record) => {  // eslint-disable-line
      if (record.isAdministrator) return '内置'
      return (
        <div>
          <Link to={`/RolePermission/EditRole?groupId=${record.groupId}`}>编辑</Link>
          <Divider type='vertical' />
          <DeleteAGQL record={record} refetch={refetch} />
        </div>
      )
    }
  }]

  return (
    <Table columns={columns} dataSource={dataSource} loading={loading} pagination={false} />
  )
}

CustomTable.propTypes = {
  dataSource: propTypes.array.isRequired,
  dispatch: propTypes.func,
  loading: propTypes.bool,
  refetch: propTypes.func
}

// 删除组件类型
Delete.propTypes = {
  delGroups: propTypes.func,
  record: propTypes.object,
  refetch: propTypes.func
}

export default CustomTable
